<template>
  <el-drawer
    title="代码值"
    size="60%"
    :visible.sync="drawerVisible"
    direction="rtl"
    :close-on-press-escape="false"
    :wrapperClosable="false"
    :destroy-on-close="true"
    :before-close="clearDrawer"
    custom-class="tag-drawer"
  >
    <div class="drawer-wrap">
      <div class="drawer-content tag-scrollbar">
        <el-form :model="editForm" label-width="120px" :rules="editFormRules" ref="editForm">
          <el-form-item label="标签名称" prop="tagId">
            <el-select v-model="editForm.tagId" filterable remote :remote-method="getTagNm" @change="changeTag">
              <el-option v-for="item in tagList" :key="item.tagId" :label="item.tagNm" :value="item.tagId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标签默认值" prop="defaultValue">
            <el-input v-model="editForm.defaultValue" placeholder="请输入标签默认值,如不填则为空"></el-input>
          </el-form-item>
          <el-form-item label="取值类型" prop="valueType">
            <el-select v-model="editForm.valueType" disabled>
              <el-option label="---" value=""></el-option>
              <el-option
                v-for="item in $dictList('value_type')"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
          <template v-if="editForm.enumTag">
            <tag-content-header search refresh @toolFun="toolFun">
              <template #title>
                <span>枚举值列表</span>
              </template>
            </tag-content-header>
            <tag-table
              ref="table"
              @refresh="getList"
              :data="dataList"
              :loading="loading"
              :columns="columns"
              :params="params"
              :total="totalSize"
              selection
              rowKey="cdVal"
            >
            </tag-table>
          </template>
          <el-form-item prop="labGrps" label="分组规则" v-else>
            <config-range :target="editForm" @addRule="addRule" @removeRule="removeRule"></config-range>
          </el-form-item>
          <el-form-item label="更新频率" prop="execFrequency">
            <el-radio-group v-model="editForm.execFrequency">
              <el-radio v-for="item in $dictList('$exec_frequency')" :key="item.key" :label="item.key">
                {{ item.value }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="editForm.execFrequency">
            <el-form-item label="执行日期" prop="execDtList" v-if="editForm.execFrequency === 2" class="rate-form">
              <el-checkbox-group v-model="editForm.execDtList">
                <el-checkbox v-for="date in 31" :label="date" :key="date">{{ date }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="执行星期" prop="execWkList" v-if="editForm.execFrequency === 3" class="rate-form">
              <el-checkbox-group v-model="editForm.execWkList">
                <el-checkbox v-for="week in 7" :label="week" :key="week">{{ weekShow(week) }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="执行时间" prop="execTm">
              <el-col :span="12">
                <el-time-picker
                  v-model="editForm.execTm"
                  size="mini"
                  placeholder="执行时间"
                  value-format="HH:mm:ss"
                ></el-time-picker>
              </el-col>
            </el-form-item>
          </template>
        </el-form>
      </div>
    </div>
    <div class="drawer-btns">
      <el-button @click="clearDrawer">关闭</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </div>
  </el-drawer>
</template>
<script>
import configRange from './config-range'
export default {
  name: 'configDrawer',
  components: {
    configRange
  },
  data() {
    return {
      drawerVisible: false,
      tagList: [],
      loading: false,
      dataList: [],
      columns: [
        {
          show: true,
          label: '枚举值',
          prop: 'cdVal',
          search: true,
          searchKey: '',
          align: 'center'
        },
        {
          show: true,
          label: '枚举值描述',
          prop: 'cdDesc',
          search: true,
          searchKey: '',
          align: 'center'
        }
      ],
      params: {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      },
      totalSize: 0,
      selectedVal: [],
      editForm: {
        tagId: '',
        tagNm: '',
        defaultValue: '',
        enumTag: '',
        valueType: '',
        execFrequency: '',
        execDtList: [],
        execWkList: [],
        execTm: '',
        labGrps: [
          {
            codeCd: '',
            codeDesc: '',
            valLft: '',
            valRit: ''
          }
        ]
      },
      editFormRules: {
        tagId: [{ required: true, message: '标签名称不能为空', trigger: 'change' }],
        execFrequency: [{ required: true, message: '取值类型不能为空', trigger: 'change' }],
        execDtList: [{ required: true, type: 'array', min: 1, message: '至少要选择一项', trigger: 'change' }],
        execWkList: [{ required: true, type: 'array', min: 1, message: '至少要选择一项', trigger: 'change' }],
        execTm: [{ required: true, message: '执行时间不能为空', trigger: 'change' }]
      }
    }
  },
  methods: {
    showDrawer(tagId) {
      this.editForm.tagId = tagId
      if (this.editForm.tagId) this.getDetail()
      this.drawerVisible = true
    },
    weekShow(week) {
      let str = ''
      switch (week) {
        case 1:
          str = '日'
          break
        case 2:
          str = '一'
          break
        case 3:
          str = '二'
          break
        case 4:
          str = '三'
          break
        case 5:
          str = '四'
          break
        case 6:
          str = '五'
          break
        case 7:
          str = '六'
          break
      }
      return str
    },
    getTagNm(query) {
      if (!query) {
        this.tagList = []
        return
      }
      this.$ajax({
        url: this.$ajax.setUrl(`mon/monTagConfig/monTagList/${query}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.tagList = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    changeTag(tagId) {
      const tag = this.tagList.find(item => item.tagId === tagId)
      if (tag) {
        this.editForm.tagNm = tag.tagNm
        this.editForm.enumTag = tag.enumTag
        this.editForm.valueType = tag.valueType
        this.getList()
      }
    },
    getDetail() {
      this.$ajax({
        url: this.$ajax.setUrl(`mon/monTagConfig/configDetail/${this.editForm.tagId}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.editForm.tagNm = data.data.tagNm
          this.editForm.defaultValue = data.data.defaultValue
          this.editForm.enumTag = data.data.enumTag
          this.editForm.valueType = data.data.valueType
          this.editForm.execFrequency = data.data.execFrequency
          this.editForm.execDtList = data.data.execDtList
          this.editForm.execWkList = data.data.execWkList
          this.editForm.execTm = data.data.execTm
          const configJson = JSON.parse(data.data.cdConfig)
          if (configJson.codeType === 'enum') {
            this.selectedVal = configJson.codeConfig
            this.getList()
          } else this.editForm.labGrps = configJson.codeConfig
          this.getTagNm(this.editForm.tagNm)
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getList() {
      this.loading = true
      this.params.queryParams.tagId = this.editForm.tagId
      this.$ajax({
        url: this.$ajax.setUrl('ast/astTagEnumVal/pageList'),
        method: 'get',
        params: this.$ajax.setParams(this.params)
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.dataList = data.data.records
          this.totalSize = data.data.totalSize
          this.selectedVal.forEach(v =>
            this.$nextTick(() => {
              let row = this.dataList.find(item => item.cdVal === v.codeCd)
              if (row) {
                let selectedRow = this.$refs.table.getSelectList()
                if (!selectedRow.find(item => item.cdVal === row.cdVal))
                  this.$refs.table.$refs.tagTable.toggleRowSelection(row)
              }
            })
          )
        } else {
          this.$message.error(data.data || data.msg)
        }
        this.loading = false
      })
    },
    toolFun(operation) {
      switch (operation) {
        case 'search':
          // 搜索动作
          this.$refs['table'].searchToggle()
          break
        case 'refresh':
          // 刷新动作
          this.getList()
          break
      }
    },
    addRule(index) {
      this.editForm.labGrps.splice(index, 0, {
        codeCd: '',
        codeDesc: '',
        valLft: index >= 0 ? this.editForm.labGrps[index - 1].valRit : '',
        valRit: ''
      })
      this.$forceUpdate()
    },
    removeRule(index) {
      this.editForm.labGrps.splice(index, 1)
      this.$forceUpdate()
    },
    submit() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          let cdConfig = {
            codeType: 'other',
            codeConfig: this.editForm.labGrps
          }
          if (this.editForm.enumTag) {
            const eunmList = this.$refs.table.getSelectList()
            if (!eunmList.length) {
              this.$message.info('请选择枚举值！')
              return
            }
            cdConfig.codeType = 'enum'
            cdConfig.codeConfig = []
            eunmList.forEach(item => cdConfig.codeConfig.push({ codeCd: item.cdVal, codeDesc: item.cdDesc }))
          }
          let params = {
            tagId: this.editForm.tagId,
            tagNm: this.editForm.tagNm,
            valueType: this.editForm.valueType,
            enumTag: this.editForm.enumTag,
            defaultValue: this.editForm.defaultValue,
            execFrequency: this.editForm.execFrequency,
            execTm: this.editForm.execTm,
            execWkList: this.editForm.execWkList,
            execDtList: this.editForm.execDtList
          }
          params.cdConfig = JSON.stringify(cdConfig)
          this.$ajax({
            url: this.$ajax.setUrl('mon/monTagConfig/saveConfig'),
            method: 'post',
            data: this.$ajax.setData(params)
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.$message.success(data.msg)
              this.clearDrawer()
              this.$emit('callback')
            } else {
              this.$message.error(data.data || data.mssg)
            }
          })
        }
      })
    },
    clearDrawer() {
      this.tagId = ''
      this.tagNm = ''
      this.defaultValue = ''
      this.enumTag = ''
      this.valueType = ''
      this.execFrequency = ''
      this.execDtList = []
      this.execWkList = []
      this.execTm = ''
      this.labGrps = [
        {
          codeCd: '',
          codeDesc: '',
          valLft: '',
          valRit: ''
        }
      ]
      this.dataList = []
      this.totalSize = 0
      this.selectedVal = []
      this.drawerVisible = false
    }
  }
}
</script>

<style lang="scss">
.alarm-code-detail-list {
  position: relative;
}
</style>
